package com.bluefox.modules.system.service.impl;

import com.bluefox.utils.PageUtil;
import com.bluefox.utils.QueryHelp;
import com.bluefox.utils.UpdateUtil;
import com.bluefox.modules.system.criteria.DictTypeCriteria;
import com.bluefox.modules.system.domain.SysDictType;
import com.bluefox.modules.system.repository.SysDictTypeRepository;
import com.bluefox.modules.system.service.SysDictTypeService;
import com.bluefox.modules.system.service.dto.SysDictTypeDto;
import com.bluefox.modules.system.service.mapper.SysDictTypeMapper;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;

import javax.annotation.Resource;
import java.util.Optional;

import org.springframework.transaction.annotation.Transactional;

/**
 * (SysDictType)表服务实现类
 *
 * @author sunfeng
 * @since 2020-05-21 15:33:50
 */
@Service("sysDictTypeService")
public class SysDictTypeServiceImpl implements SysDictTypeService {
    @Resource
    private SysDictTypeRepository sysDictTypeRepository;

    @Resource
    private SysDictTypeMapper sysDictTypeMapper;



    @Override
    public Object getAll(Pageable pageable) {

        Page<SysDictType> page = this.sysDictTypeRepository.findAll(pageable);


        return  PageUtil.toPage(page.map(sysDictTypeMapper::toDto));

    }

    @Override
    public Object getAll(DictTypeCriteria criteria, Pageable pageable) {

        Page<SysDictType> page = this.sysDictTypeRepository.findAll((Specification<SysDictType>) (root, query, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);

        return PageUtil.toPage(page.map(sysDictTypeMapper::toDto));
    }

    @Override
    @Transactional
    public SysDictTypeDto insert(SysDictTypeDto sysDictType) {

        SysDictType dictType = new SysDictType();

        UpdateUtil.copyNullProperties(sysDictType,dictType);

        return this.sysDictTypeMapper.toDto(sysDictTypeRepository.save(dictType)) ;
    }

    @Override
    @Transactional
    public void deleteById(Long[] dictIds) {
        for (Long dictId:dictIds) {
            sysDictTypeRepository.deleteById(dictId);
        }
    }

    @Override
    public SysDictTypeDto queryById(Long dictId) {
        Optional<SysDictType> sysDictType = sysDictTypeRepository.findById(dictId);

        return sysDictType.map(dictType -> sysDictTypeMapper.toDto(dictType)).orElse(null);
    }

    @Override
    @Transactional
    public SysDictTypeDto update(SysDictTypeDto dictType) {
        SysDictType sysDictType = sysDictTypeRepository.findById(dictType.getId()).get();
        UpdateUtil.copyNullProperties(dictType, sysDictType);
        return sysDictTypeMapper.toDto(sysDictTypeRepository.save(sysDictType));
    }

}
